//
//  String+Extesion.swift
//  Teamo
//
//  Created by mdzz on 2021/12/7.
//

import Foundation
import UIKit

extension String {
    /// 定义不可用 id
    static let invalidID: String = String(Int64.max)
}

extension String {
    /// 字符串直接生成image "image_name".image
    /// - Returns: image
    public  var image: UIImage {
        return UIImage(named: self as String) ?? UIImage()
    }
}
extension String {
    
    /// 字符串宽度
    /// - Parameters:
    ///   - font: font description
    ///   - height: height description
    /// - Returns: description
    public func width(font: UIFont, height: CGFloat = 20) -> CGFloat {
        guard self.isEmpty == false else {
            return 0
        }
        let rect = NSString(string: self).boundingRect(with: CGSize(width: CGFloat(MAXFLOAT), height: height), options: .usesLineFragmentOrigin, attributes: [.font: font], context: nil)
        return ceil(rect.width)
    }

    /// 字符串高度
    /// - Parameters:
    ///   - font: font description
    ///   - width: width description
    /// - Returns: description
    public func height(font: UIFont, width: CGFloat = 20) -> CGFloat {
        guard self.isEmpty == false else {
            return 0
        }
        let rect = NSString(string: self).boundingRect(with: CGSize(width: width, height: CGFloat(MAXFLOAT)), options: .usesLineFragmentOrigin, attributes: [.font: font], context: nil)
        return ceil(rect.height)
    }
}


extension String {
    
    /// string转json
    public var json: [String:Any]? {
        if let data = self.data(using: .utf8, allowLossyConversion: false) {
            let message = try? JSONSerialization.jsonObject(with: data)
            return message as? [String:Any]
        } else {
            return nil
        }
    }
    
    /// NSRange
    public func nsRange(from range: Range<String.Index>) -> NSRange {
        return NSRange(range, in: self)
    }
}


//class func madEncryptWidth(_ string: String) -> String? {
//    if let str = string.cString(using: .utf8) {
//        let strLen = CC_LONG(string.lengthOfBytes(using: .utf8))
//        let digestLen = Int(CC_MD5_DIGEST_LENGTH)
//        let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
//
//        CC_MD5(str, strLen, result)
//
//        let hash = NSMutableString()
//        for i in 0 ..< digestLen {
//            hash.appendFormat("%02x", result[i])
//        }
//
//        result.deinitialize(count: digestLen)
//
//        return hash as String
//    }
//    return nil
//}
